<template>
  <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click="handleBackdropClick">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white" @click.stop>
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-lg font-semibold text-gray-900">
          {{ isEdit ? '编辑用户' : '新增用户' }}
        </h3>
        <button @click="$emit('close')" class="text-gray-400 hover:text-gray-600">
          <XMarkIcon class="h-6 w-6" />
        </button>
      </div>

      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700 mb-2">用户名 *</label>
            <input 
              type="text" 
              id="username" 
              v-model="form.username" 
              required 
              :disabled="isEdit"
              placeholder="请输入用户名" 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm disabled:bg-gray-100 disabled:cursor-not-allowed" 
            />
            <p v-if="isEdit" class="mt-1 text-xs text-gray-500">编辑模式下用户名不可修改</p>
          </div>
          <div>
            <label for="email" class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
            <input 
              type="email" 
              id="email" 
              v-model="form.email" 
              placeholder="请输入邮箱地址" 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" 
            />
          </div>
        </div>

        <!-- 密码设置 -->
        <div v-if="!isEdit" class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="password" class="block text-sm font-medium text-gray-700 mb-2">密码 *</label>
            <input 
              type="password" 
              id="password" 
              v-model="form.password" 
              required 
              placeholder="请输入密码" 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" 
            />
          </div>
          <div>
            <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-2">确认密码 *</label>
            <input 
              type="password" 
              id="confirmPassword" 
              v-model="form.confirmPassword" 
              required 
              placeholder="请再次输入密码" 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" 
            />
          </div>
        </div>

        <!-- 角色和实验室 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="role" class="block text-sm font-medium text-gray-700 mb-2">角色 *</label>
            <select 
              id="role" 
              v-model="form.role" 
              required 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            >
              <option value="">请选择角色</option>
              <option value="ADMIN">系统管理员</option>
              <option value="LEADER">上级领导</option>
              <option value="LAB_MANAGER">实验室管理员</option>
            </select>
          </div>
          <div>
            <label for="laboratory" class="block text-sm font-medium text-gray-700 mb-2">所属实验室</label>
            <select 
              id="laboratory" 
              v-model="form.laboratory" 
              :disabled="form.role === 'ADMIN' || form.role === 'LEADER'"
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm disabled:bg-gray-100 disabled:cursor-not-allowed"
            >
              <option value="">请选择实验室</option>
              <option value="计算机实验室A">计算机实验室A</option>
              <option value="计算机实验室B">计算机实验室B</option>
              <option value="化学实验室">化学实验室</option>
              <option value="生物实验室">生物实验室</option>
              <option value="物理实验室">物理实验室</option>
            </select>
            <p v-if="form.role === 'ADMIN' || form.role === 'LEADER'" class="mt-1 text-xs text-gray-500">系统管理员和上级领导不需要分配实验室</p>
          </div>
        </div>

        <!-- 状态设置 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="status" class="block text-sm font-medium text-gray-700 mb-2">状态 *</label>
            <select 
              id="status" 
              v-model="form.status" 
              required 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            >
              <option value="ACTIVE">正常</option>
              <option value="INACTIVE">禁用</option>
            </select>
          </div>
          <div>
            <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">联系电话</label>
            <input 
              type="tel" 
              id="phone" 
              v-model="form.phone" 
              placeholder="请输入联系电话" 
              class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" 
            />
          </div>
        </div>

        <!-- 备注 -->
        <div>
          <label for="remarks" class="block text-sm font-medium text-gray-700 mb-2">备注</label>
          <textarea 
            id="remarks" 
            v-model="form.remarks" 
            rows="3" 
            placeholder="请输入备注信息" 
            class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
          ></textarea>
        </div>

        <!-- 按钮组 -->
        <div class="flex justify-end space-x-4 pt-6 border-t border-gray-200">
          <button 
            type="button" 
            @click="$emit('close')" 
            class="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
          >
            取消
          </button>
          <button 
            type="submit" 
            :disabled="loading" 
            class="px-6 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="loading">保存中...</span>
            <span v-else>{{ isEdit ? '更新' : '创建' }}</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { XMarkIcon } from '@heroicons/vue/24/outline'

// Props
const props = defineProps({
  user: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['close', 'save'])

// 响应式数据
const loading = ref(false)

const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  role: '',
  laboratory: '',
  status: 'ACTIVE',
  phone: '',
  remarks: ''
})

// 监听角色变化，清空实验室选择
watch(() => form.role, (newRole) => {
  if (newRole === 'ADMIN' || newRole === 'LEADER') {
    form.laboratory = ''
  }
})

// 监听用户数据变化，填充表单
watch(() => props.user, (newUser) => {
  if (newUser) {
    Object.assign(form, {
      username: newUser.username || '',
      email: newUser.email || '',
      password: '',
      confirmPassword: '',
      role: newUser.role || '',
      laboratory: newUser.laboratoryName || '',
      status: newUser.status || 'ACTIVE',
      phone: newUser.phone || '',
      remarks: newUser.remarks || ''
    })
  }
}, { immediate: true })

// 方法
const handleBackdropClick = (event) => {
  if (event.target === event.currentTarget) {
    emit('close')
  }
}

const validateForm = () => {
  if (!form.username.trim()) {
    showMessage('请输入用户名', 'error')
    return false
  }
  
  if (!form.role) {
    showMessage('请选择角色', 'error')
    return false
  }
  
  if (!props.isEdit) {
    if (!form.password) {
      showMessage('请输入密码', 'error')
      return false
    }
    
    if (form.password !== form.confirmPassword) {
      showMessage('两次输入的密码不一致', 'error')
      return false
    }
    
    if (form.password.length < 6) {
      showMessage('密码长度不能少于6位', 'error')
      return false
    }
  }
  
  if (form.role === 'LAB_MANAGER' && !form.laboratory) {
    showMessage('实验室管理员必须分配实验室', 'error')
    return false
  }
  
  if (form.email && !isValidEmail(form.email)) {
    showMessage('请输入有效的邮箱地址', 'error')
    return false
  }
  
  return true
}

const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  try {
    loading.value = true
    
    // 准备提交数据
    const userData = {
      username: form.username.trim(),
      email: form.email.trim() || null,
      role: form.role,
      laboratory: form.laboratory || null,
      status: form.status,
      phone: form.phone.trim() || null,
      remarks: form.remarks.trim() || null
    }
    
    // 如果是创建用户，添加密码
    if (!props.isEdit) {
      userData.password = form.password
    }
    
    // 如果是编辑用户，添加ID
    if (props.isEdit && props.user) {
      userData.id = props.user.id
    }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('save', userData)
    
  } catch (error) {
    console.error('保存用户失败:', error)
    showMessage('保存用户失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息提示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  // 如果是编辑模式，填充表单数据
  if (props.isEdit && props.user) {
    Object.assign(form, {
      username: props.user.username || '',
      email: props.user.email || '',
      password: '',
      confirmPassword: '',
      role: props.user.role || '',
      laboratory: props.user.laboratoryName || '',
      status: props.user.status || 'ACTIVE',
      phone: props.user.phone || '',
      remarks: props.user.remarks || ''
    })
  }
})
</script>